import {
  Component,
  OnInit,
  OnChanges,
  ViewChild,
  Input,
  SimpleChanges,
  Output,
  EventEmitter
} from '@angular/core';
import { MatTableDataSource, MatTable } from '@angular/material/table';
import { StepConfig } from '../../model/step-config.model';
import { MatDialog, MatMenuTrigger } from '@angular/material';
import { AddStepComponent } from '../add-step/add-step.component';
import { SelectionModel } from '@angular/cdk/collections';

@Component({
  selector: 'app-scenario',
  templateUrl: './scenario.component.html',
  styleUrls: ['./scenario.component.css']
})
export class ScenarioComponent implements OnInit, OnChanges {

  @Input()
  stepConfigs: any;

  @Output()
  save = new EventEmitter<null>();

  @ViewChild(MatTable)
  table: MatTable<MatTableDataSource<StepConfig>>;

  @ViewChild(MatMenuTrigger)
  contentMenu: MatMenuTrigger;

  meunPosition = {
    'left.px': 0,
    'top.px': 0,
  };

  contextMenuOnRow = null;

  displayedColumns: string[] = ['select', 'stepNo', 'action', 'mode', 'target', 'value'];
  dataSource = new MatTableDataSource<StepConfig>();
  selection = new SelectionModel<StepConfig>(true, []);

  constructor(private dialog: MatDialog) {
    this.dataSource.data = [];
  }

  get data() {
    return this.dataSource.data;
  }

  ngOnInit() {
  }

  ngOnChanges(changes: SimpleChanges) {
    const { stepConfigs } = changes;
    if (stepConfigs.currentValue && this.table.dataSource) {
      this.dataSource.data = stepConfigs.currentValue.config;
      this.table.renderRows();
    }
  }

  addRow() {
    const dialogRef = this.dialog.open(AddStepComponent, {
      data: { title: '新建步骤' }
    });
    dialogRef.afterClosed().subscribe(
      config => {
        if (config) {
          this.dataSource.data.push({ ...config, stepNo: this.dataSource.data.length + 1 });
          this.table.renderRows();
        }
      }
    );
  }

  run() {
    console.log('run!');
  }

  saveConfig() {
    this.save.emit();
  }

  clickRow(row) {
    const dialogRef = this.dialog.open(AddStepComponent, {
      data: { ...row, title: '修改步骤' }
    });
    dialogRef.afterClosed().subscribe(
      config => {
        if (config) {
          const index = this.dataSource.data.indexOf(row);
          this.dataSource.data[index] = config;
          this.table.renderRows();
        }
      }
    );
  }

  openContextMenu(e: MouseEvent, row) {
    e.preventDefault();
    this.meunPosition['left.px'] = e.x - 300;
    this.meunPosition['top.px'] = e.y - 64;
    this.contentMenu.openMenu();
    this.contextMenuOnRow = row;
  }

  onContextMenuDelete() {
    const row = this.contextMenuOnRow;
    if (this.selection.isSelected(row)) {
      this.selection.deselect(row);
    }
    this.dataSource.data = this.dataSource.data.filter(d => d !== row);
  }

  onContextMenuCopy() {
    const row = this.contextMenuOnRow;
  }

  delete() {
    this.dataSource.data = this.dataSource.data.filter(d => !this.selection.isSelected(d));
    this.selection.clear();
  }

  /** Whether the number of selected elements matches the total number of rows. */
  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.dataSource.data.length;
    return numSelected === numRows;
  }

  /** Selects all rows if they are not all selected; otherwise clear selection. */
  masterToggle() {
    this.isAllSelected() ?
        this.selection.clear() :
        this.dataSource.data.forEach(row => this.selection.select(row));
  }

}
